import base64

import openpyxl
import xlrd


def read_file_txt(url):
    """
    读取文本文件
    :param url: 文本文件地址
    :return:
    """
    with open(url, mode='r', encoding='utf-8') as f:
        read = f.read()
        strip = read.rstrip()
        print(strip)


def read_file_by_line_by_one_inst(url):
    """
    按行读取文本文件
    :param url: 文本文件地址
    :return:
    """
    file_handler = open(url, 'r', encoding='utf-8')
    read_lines = file_handler.readlines()
    file_handler.close()
    for line in read_lines:
        print(line.strip())


def read_file_by_line_by_mutil_inst(url):
    """
    全部读取按行输出文本文件
    :param url: 文本文件地址
    :return:
    """
    file_handler = open(url, 'r', encoding='utf-8')
    while True:
        readline = file_handler.readline()
        if not readline:
            break
        print(readline.strip())
    file_handler.close()


def image_to_base64(url, base_url):
    """
    图片转base64
    :param url: 图片地址
    :param base_url: base64文件地址
    :return:
    """
    with open(url, "rb") as f:  # 转为二进制格式
        base64_data = base64.b64encode(f.read())  # 使用base64进行加密
        print(base64_data)
        file = open(base_url, 'wb')  # 写成文本格式
        file.write(base64_data)
        file.close()


def base64_to_image(url, image_url):
    """
    base64转图片
    :param url: base64文件地址
    :param image_url: 图片地址
    :return:
    """
    with open(url, "r") as f:
        imgdata = base64.b64decode(f.read())
        file = open(image_url, 'wb')
        file.write(imgdata)
        file.close()


def read_xls(url):
    """
    读取excel，支持xls
    :param url: excel文件地址
    :return:
    """
    xls = xlrd.open_workbook_xls(url)
    sheet1 = xls.sheets()[0]
    rows = sheet1.nrows
    print(rows)
    for i in range(rows):
        row = sheet1.row_values(i)
        print(row)


def read_xlsx(url):
    """
    读取excel，仅支持xlsx
    :param url: excel文件地址
    :return:
    """
    workbook = openpyxl.load_workbook(url)
    sheets = workbook.worksheets[0]
    rows = sheets.rows
    return rows
    # for row in rows:
    #     print(row)
